<!DOCTYPE html>
<html>
<head>

    <title>在线寄件</title>
    <script src="/home/js/jquery-1.11.2.js"></script>
    <script src="/home/js/jquery.page.js"></script>
    <script src="/home/js/jquery.cookie.js"></script>
    <script src="/home/js/idangerous.swiper.min.js"></script>
    <script src="/home/js/layer.js"></script>
    <link rel="stylesheet" href="/home/css/layer.css" id="layuicss-skinlayercss">
    <script src="/home/js/baseUtility.js"></script>
    <script src="/home/js/edit.js"></script>
    <link href="/home/css/List.css" rel="stylesheet">
    <link href="/home/css/pager.css" rel="stylesheet">
    <script type="text/javascript">
        // 将 layer 弹窗对象注入到相应的命名空间，以供使用
        addressEditNameSpace.setLayer(layer);
        (function (w) {
            if (!("WebSocket" in w && 2 === w.WebSocket.CLOSING)) {
                var d = document.createElement("div");
                d.className = "browsehappy";
                d.innerHTML =
                    '<div style="width:100%;height:100px;font-size:30px;line-height:100px;text-align:center;background-color:#ee6900;color:#fff;margin-bottom:40px;">\u60a8\u7684\u6d4f\u89c8\u5668\u7248\u672c\u5b9e\u5728\u662f<strong>\u592a\u65e7\u4e86<\strong><a target="_blank" href="https://www.baidu.com/link?url=Z-k_dgvBnkwwMefWJx8Oa3XDCX3vlYffDo9gXrgGdrjvbt5o2YlxK9fXCsBjMMvXptcPtPfScTviYuXj67uXQOGt-GDfyKRDfg0bxZ-p-mq&wd=&eqid=df5151c400006c2f000000055a56cfef" style="background-color:#31b0d5;border-color: #269abc;text-decoration: none;padding: 6px 12px;background-image: none;border: 2px solid transparent;border-radius: 4px;color:#FFEB3B;">\u7acb\u5373\u5347\u7ea7</a></div>';
                var f = function () {
                    var s = document.getElementsByTagName("body")[0];
                    if ("undefined" == typeof (s)) {
                        setTimeout(f, 10)
                    } else {
                        s.insertBefore(d, s.firstChild)
                    }
                };
                f()
            }
        }(window));
    </script>
    <link rel="stylesheet" type="text/css" href="/home/css/common.css">
    <script src="/home/js/html5.js"></script>
    <link href="/home/css/WdatePicker.css" rel="stylesheet" type="text/css">
    <link id="layuicss-layer" rel="stylesheet" href="/home/css/layer(1).css" media="all">
</head>
<body style="">

<#--引入头部和顶部导航栏-->
<#include "../common/header.ftl"/>
<#include "../common/top_nav.ftl"/>

<div class="box" style="min-height:800px;">
    <script src="/home/js/jquery.min.js"></script>
    <link href="/home/css/jquery-ui.min.css" rel="stylesheet">
    <script src="/home/js/jquery-ui.min.js"></script>
    <link href="/home/css/city-picker.css" rel="stylesheet">
    <link href="/home/css/BatchOrder.css" rel="stylesheet">
    <link href="/home/layui/css/layui.css" rel="stylesheet">
    <script src="/home/layui/layui.js"></script>
    <script src="/home/js/WdatePicker.js"></script>
    <script src="/home/js/jquery.tmpl.min.js"></script>
    <script src="/home/js/city-picker.data.js"></script>
    <script src="/home/js/city-picker.js"></script>
    <script src="/home/js/jquery.cookie.js"></script>
    <script src="/home/js/OrderAddress.js"></script>
    <style>
        .right table tbody tr {
            height: 20px;
            line-height: 20px;
        }
    </style>
    <div class="banner"></div>
    <div class="alert" style="display:none">
        <div class="alertBox">
            <div class="alertContent">
                取件时间：16:30前下单正常当天完成取件 | 16:30后下单默认次日18:00前完成取件
            </div>
        </div>
    </div>
    <form id="orderForm">
        <div id="log"></div>
        <#--        <input type="hidden" name="UserId" id="hiddenUserId" value="">-->
        <div class="content">
            <div class="ordertype">
                <div class="title">
                    <p style="padding-top:6px;">选</p>
                    <p>择</p>
                </div>
                <a class="signalorder" href="/home/entryPage/singletonPage">单件下单</a>
                <a class="signalorder" href="/home/entryPage/bulkOrderPage">批量下单</a>
            </div>
            <input type="hidden" name="homeUser.id" value="${homeUser.id}">
            <div class="sendUser clearfix">
                <div class="title">
                    <p style="padding-top:53px;">寄</p>
                    <p>件</p>
                    <p>人</p>
                    <p>信</p>
                    <p>息</p>
                </div>
                <div class="SendUserInfo" style="float:left; width:960px">
                    <div class="line clearfix">
                        <div class="left">
                            <label>姓名：</label>
                            <input id="senderName" value="<#if defaultSenderInfo??>${defaultSenderInfo.name}</#if>"
                                   name="senderName" maxlength="32" placeholder="请输入寄件人姓名">
                        </div>
                        <div class="order_text_img">
                            <a class="order_address_list">
                                <img src="/home/images/order.png" width="35" height="35">
                            </a>
                        </div>
                        <div class="right ui-widget">
                            <label>手机号码：</label>
                            <span role="status" aria-live="polite" class="ui-helper-hidden-accessible"></span><input
                                    id="senderMobile" value="<#if defaultSenderInfo??>${defaultSenderInfo.mobile}</#if>"
                                    name="senderMobile" maxlength="13" placeholder="请输入寄件人手机号码"
                                    class="ui-autocomplete-input" autocomplete="off">
                        </div>
                    </div>
                    <div class="line clearfix">
                        <div class="left">
                            <label>发件地址：</label>
                            <div style="display:inline-block;position:relative">
                                <input id="sendFullAddress" data-toggle="city-picker"
                                       value="<#if defaultSenderInfo??>${defaultSenderInfo.address}</#if>" type="text"
                                       name="sendFullAddress"
                                       readonly="readonly"
                                       placeholder="请选择省市区" class="city-picker-input"><span class="city-picker-span"
                                                                                            style="width:280px;height:40px;line-height:39px;"><span
                                            class="placeholder">请选择省市区</span><span class="title"
                                                                                   style="display: none;"></span>
											<div class="arrow"></div>
										</span>
                            </div>

                        </div>
                        <div class="right">
                            <label>详细地址：</label>
                            <input id="sendAddress"
                                   value="<#if defaultSenderInfo??>${defaultSenderInfo.detailedAddress}</#if>"
                                   name="sendAddress" maxlength="100"
                                   placeholder="xx路xx号xx小区x幢x单元xx">
                        </div>
                    </div>

                    <div class="line clearfix">
                        <div class="left">
                            <label>座机号码：</label>
                            <input id="senderLandlineNumber"
                                   value="<#if defaultSenderInfo??>${defaultSenderInfo.phone}</#if>"
                                   name="senderLandlineNumber" maxlength="18" placeholder="请输入寄件人座机号码">
                        </div>
                        <div class="right">
                            <label>邮箱：</label>
                            <input id="senderEmail" name="senderEmail" maxlength="50" placeholder="此邮箱用于接受下单进度提醒">
                        </div>
                    </div>

                    <div class="line clearfix">

                        <div class="left">
                            <label>付款方式：</label>
                            <select id="paymentMethod" name="paymentMethod">
                                <option value="请选择付款方式">请选择付款方式</option>
                                <#list paymentMethodEnum as paymentMethodEnum>
                                    <option value="${paymentMethodEnum}">${paymentMethodEnum.getName()}</option>
                                </#list>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
            <div class="putUser clearfix">
                <div class="title">
                    <p style="padding-top:133px;">收</p>
                    <p>件</p>
                    <p>人</p>
                    <p>及</p>
                    <p>物</p>
                    <p>品</p>
                    <p>信</p>
                    <p>息</p>
                </div>
                <div class="putUserInfo" style="float:left; width:960px">
                    <div class="buttonExcel">
                        <a class="downloadTip">请按excel表格规定录入数据，导入后默认只展示验证通过的数据</a>
                        <a class="downloadExcel" href="/download/importTemplate" id="downloadExcel">下载excel模板</a>
                        <a class="downloadExcel" id="datatable" onclick="selectFile()" name="datatable">导入excel数据</a>
                        <input class="layui-upload-file" id="upload-file" type="file" name="file">
                        <a class="downloadExcel" id="deleteCheck" name="deleteCheck" onclick="DelOrderData()">删除</a>
                    </div>


                    <div id="result" class="right">


                        <table border="0" cellpadding="0" cellspacing="0">
                            <tbody id="resultTbody">
                            <tr class="titleBox">
                                <th class="titlecheck" height="20">
                                    <input type="checkbox" name="AllcheckId" id="AllcheckId" style="width:15px">
                                </th>
                                <th class="titleName">姓名</th>
                                <th class="titleTel">手机号</th>
                                <th class="titleTel">座机号</th>
                                <th class="titleName">省</th>
                                <th class="titleTel">市</th>
                                <th class="titleName">区(县)</th>
                                <th class="titleTel">详细地址</th>
                                <th class="titleName">物品类型</th>
                                <th class="titleTel">重量</th>
                                <th class="titleOperate">备注</th>
                            </tr>

                            </tbody>


                        </table>
                    </div>
                </div>
            </div>
            <div class="create_order_more_page_box"></div>
            <div class="submitBox">
                <p class="submitBtn">
                    <input type="button" id="orderSubmit" value="提交订单">
                </p>
            </div>
        </div>
    </form>

    <script src="/home/js/BatchOrder.js"></script>
</div>


<div id="orderAddressListDiv" style="display: none" class="orderAaddress">
    <div class="order_address_title"></div>
    <table class="layui-table">
        <thead>
        <tr style="background-color: #ee6900;color:#ffffff">
            <th>操作</th>
            <th>类别</th>
            <th>姓名</th>
            <th>手机号</th>
            <th>座机号</th>
            <th>地址</th>
        </tr>
        </thead>
        <tbody>
        <#if senderInfoList?size gt 0>
            <#list senderInfoList as senderInfo>
                <tr>
                    <td align="center">
                        <input style="cursor: pointer" class="checkbox_selected" name="checkbox" type="radio" id="${senderInfo.id}">
                    </td>
                    <td>${senderInfo.homeUserType.getName()}</td>
                    <td>${senderInfo.name}</td>
                    <td>${senderInfo.mobile}</td>
                    <td>${senderInfo.phone!""}</td>
                    <td>${senderInfo.address}-${senderInfo.detailedAddress}</td>
                </tr>
            </#list>
        </#if>
        <tr>
            <td colspan="6" align="center"><a class="sendAddress_shure" onclick="listCallBack()">确定</a>
            </td>
        </tr>
        </tbody>
    </table>
</div>

<#--尾部-->
<#include "../common/footer.ftl"/>


<ul class="ui-autocomplete ui-front ui-menu ui-widget ui-widget-content ui-corner-all" id="ui-id-1" tabindex="0"
    style="display: none;"></ul>


<script src="/home/xlsx/xlsx.core.min.js"></script>
<script type="text/javascript">

    $("#AllcheckId").change(function (e) {
        //alert(this.checked);
        if (this.checked) {
            $("input[name='checkId']").each(function (i, dom) {
                $(this).prop("checked", true);
            });
        } else {
            $("input[name='checkId']").each(function (i, dom) {
                $(this).prop("checked", false);
            });
        }
    });

    function selectFile() {
        $("#upload-file").click();
    }

    // 读取本地excel文件
    function readWorkbookFromLocalFile(file, callback) {
        var reader = new FileReader();
        reader.onload = function (e) {
            var data = e.target.result;
            var workbook = XLSX.read(data, {type: 'binary'});
            if (callback) callback(workbook);
        };
        reader.readAsBinaryString(file);
    }

    // 读取excel文件
    function outputWorkbook(workbook) {
        var sheetNames = workbook.SheetNames; // 工作表名称集合
        sheetNames.forEach(name => {
            var worksheet = workbook.Sheets[name]; // 只能通过工作表名称来获取指定工作表
            for (var key in worksheet) {
                // v是读取单元格的原始值
                console.log(key, key[0] === '!' ? worksheet[key] : worksheet[key].v);
            }
        });
    }

    function readWorkbook(workbook) {
        var sheetNames = workbook.SheetNames; // 工作表名称集合
        var worksheet = workbook.Sheets[sheetNames[0]]; // 这里我们只读取第一张sheet
        var csv = XLSX.utils.sheet_to_csv(worksheet);
        // document.getElementById('resultTbody').innerHTML = csv2table(csv);
        $("#resultTbody").append(csv2table(csv));
    }

    // 将csv转换成表格
    function csv2table(csv) {
        var html;
        var rows = csv.split('\n');

        var rowss = new Array();

        for (var i = 0; i < rows.length; i++) {
            if (i >= 5) {
                rowss.push(rows[i])
            }
        }


        rowss.pop(); // 最后一行没用的
        rowss.forEach(function (row, idx) {
            var columns = row.split(',');
            if (columns.length != 10) {
                layer.msg("导入excel格式不正确");
                return
            }
            if (!/(^[\u4E00-\u9FA5]+$)|(^[\u4E00-\u9FA5]*·[\u4E00-\u9FA5]*$)/.test(columns[0])) {
                layer.msg("excel表格中第" + (idx + 3) + "行" + "收件人姓名格式不正确!无法完成导入!");
                return
            }
            if (columns[2] != "") {
                if ((!columns[2].match(/^0[\d]{2,3}-[\d]{7,8}(-[\d]{4,4})?$/)) && !columns[2].match(/^400(\d{7}|-\d{4}-\d{3})$/)) {
                    layer.msg("excel表格中第" + (idx + 3) + "行" + "收件人固话格式不正确!无法完成导入!");
                    return
                }
            }
            if (columns[1].length > 11) {
                layer.msg("excel表格中第" + (idx + 3) + "行" + "收件人手机号码不正确!无法完成导入!");
                return
            }

            var province = columns[3].substr(columns[3].length - 1, 1);
            var city = columns[4].substr(columns[4].length - 1, 1);
            var district = columns[5].substr(columns[5].length - 1, 1);

            if (province != "省") {
                layer.msg("excel表格中第" + (idx + 3) + "行" + "收件人省填写错误!无法完成导入!");
                return
            }

            if (city != "市") {
                layer.msg("excel表格中第" + (idx + 3) + "行" + "收件人市填写错误!无法完成导入!");
                return
            }

            if (district != "区") {
                layer.msg("excel表格中第" + (idx + 3) + "行" + "收件人区填写错误!无法完成导入!");
                return
            }


            if (columns[6] == "") {
                layer.msg("excel表格中第" + (idx + 3) + "行" + "收件人详细地址填写错误!无法完成导入!");
                return
            }

            if (columns[6].length > 50) {
                layer.msg("excel表格中第" + (idx + 3) + "行" + "收件人详细地址长度不能超过50!无法完成导入!");
                return
            }

            if (Number(columns[8]) > 50 || Number(columns[8]) <= 0) {
                layer.alert("excel表格中第" + (idx + 3) + "行" + "重量不得大于50kg或小于等于0kg!无法完成导入!");
                return
            }

            html += '<tr>';

            html += "<td class=\"titleBox\" width=\"80\">\n" +
                "                                    <input type=\"checkbox\" name=\"checkId\" value=" + idx + 1 + " style=\"width:15px\"/>\n" +
                "                                    <input type=\"hidden\" value=\"\" />\n" +
                "                                </td>"

            for (var k = 0; k < columns.length; k++) {
                html += '<td style = line-height:20px class="tableName1">' + columns[k] + '</td>';
            }

            html += '</tr>';
        });
        return html;
    }

    function table2csv(table) {
        var csv = [];
        $(table).find('tr').each(function () {
            var temp = [];
            $(this).find('td').each(function () {
                temp.push($(this).html());
            })
            temp.shift(); // 移除第一个
            csv.push(temp.join(','));
        });
        csv.shift();
        return csv.join('\n');
    }

    // csv转sheet对象
    function csv2sheet(csv) {
        var sheet = {}; // 将要生成的sheet
        csv = csv.split('\n');
        csv.forEach(function (row, i) {
            row = row.split(',');
            if (i == 0) sheet['!ref'] = 'A1:' + String.fromCharCode(65 + row.length - 1) + (csv.length - 1);
            row.forEach(function (col, j) {
                sheet[String.fromCharCode(65 + j) + (i + 1)] = {v: col};
            });
        });
        return sheet;
    }

    // 将一个sheet转成最终的excel文件的blob对象，然后利用URL.createObjectURL下载
    function sheet2blob(sheet, sheetName) {
        sheetName = sheetName || 'sheet1';
        var workbook = {
            SheetNames: [sheetName],
            Sheets: {}
        };
        workbook.Sheets[sheetName] = sheet;
        // 生成excel的配置项
        var wopts = {
            bookType: 'xlsx', // 要生成的文件类型
            bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
            type: 'binary'
        };
        var wbout = XLSX.write(workbook, wopts);
        var blob = new Blob([s2ab(wbout)], {type: "application/octet-stream"});

        // 字符串转ArrayBuffer
        function s2ab(s) {
            var buf = new ArrayBuffer(s.length);
            var view = new Uint8Array(buf);
            for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
            return buf;
        }

        return blob;
    }

    /**
     * 通用的打开下载对话框方法，没有测试过具体兼容性
     * @param url 下载地址，也可以是一个blob对象，必选
     * @param saveName 保存文件名，可选
     */
    function openDownloadDialog(url, saveName) {
        if (typeof url == 'object' && url instanceof Blob) {
            url = URL.createObjectURL(url); // 创建blob地址
        }
        var aLink = document.createElement('a');
        aLink.href = url;
        aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
        var event;
        if (window.MouseEvent) event = new MouseEvent('click');
        else {
            event = document.createEvent('MouseEvents');
            event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        }
        aLink.dispatchEvent(event);
    }

    $(function () {
        $("#upload-file")[0].addEventListener('change', function (e) {
            var files = e.target.files;
            if (files.length == 0) return;
            var f = files[0];
            if (!/\.xlsx$/g.test(f.name)) {
                alert('仅支持读取xlsx格式！');
                return;
            }
            readWorkbookFromLocalFile(f, function (workbook) {
                readWorkbook(workbook);
            });
        });
    });


    function exportExcel() {
        var csv = table2csv($('#result table')[0]);
        var sheet = csv2sheet(csv);
        var blob = sheet2blob(sheet);
        openDownloadDialog(blob, '导出.xlsx');
    }

    function exportSpecialExcel() {
        var aoa = [
            ['主要信息', null, null, '其它信息'], // 特别注意合并的地方后面预留2个null
            ['姓名', '性别', '年龄', '注册时间'],
            ['张三', '男', 18, new Date()],
            ['李四', '女', 22, new Date()]
        ];
        var sheet = XLSX.utils.aoa_to_sheet(aoa);
        sheet['!merges'] = [
            // 设置A1-C1的单元格合并
            {s: {r: 0, c: 0}, e: {r: 0, c: 2}}
        ];
        openDownloadDialog(sheet2blob(sheet), '单元格合并示例.xlsx');
    }
</script>
</body>
</html>
